package com.bishe.o2oo.web.shopadmin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.bishe.o2oo.dto.ImageHolder;
import com.bishe.o2oo.dto.ShopExecution;
import com.bishe.o2oo.entity.Area;
import com.bishe.o2oo.entity.PersonInfo;
import com.bishe.o2oo.entity.Shop;
import com.bishe.o2oo.entity.ShopCategory;
import com.bishe.o2oo.enums.ShopStateEnum;
import com.bishe.o2oo.exceptions.ShopOperationException;
import com.bishe.o2oo.service.AreaService;
import com.bishe.o2oo.service.ShopCategoryService;
import com.bishe.o2oo.service.ShopService;
import com.bishe.o2oo.util.CodeUtil;
import com.bishe.o2oo.util.HttpServletRequestUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
@RequestMapping("/shopadmin")
public class ShopManagementController {
	@Autowired
	private ShopService shopService;
	@Autowired
	private ShopCategoryService shopCategoryService;
	@Autowired
	private AreaService areaService;
	
	@RequestMapping(value = "/getshopmanagementinfo", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getShopManagementInfo(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		long shopId = HttpServletRequestUtil.getLong(request, "shopId");
		if (shopId <= 0) {
			Object currentShopObj = request.getSession().getAttribute("currentShop");//如果前端未传值，就通过session获取
			if (currentShopObj == null) {//如果还是为空，则重定向到之前的页面
				modelMap.put("redirect", true);
				modelMap.put("url", "/o2oo/shopadmin/shoplist");
			} else {
				Shop currentShop = (Shop) currentShopObj;
				modelMap.put("redirect", false);
				modelMap.put("shopId", currentShop.getShopId());
			}
		} else {
			Shop currentShop = new Shop();
			currentShop.setShopId(shopId);
			request.getSession().setAttribute("currentShop", currentShop);
			modelMap.put("redirect", false);
		}
		return modelMap;
	}
	@RequestMapping(value = "/getshoplist", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getShopList(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();//用来接收返回值
		PersonInfo user = (PersonInfo) request.getSession().getAttribute("user");
	
		//user=(PersonInfo)request.getSession().getAttribute("user");
		try {
			Shop shopCondition = new Shop();
			shopCondition.setOwner(user);
			ShopExecution se = shopService.getShopList(shopCondition, 0, 100);
			modelMap.put("shopList", se.getShopList());
			// 列出店铺成功之后，将店铺放入session中作为权限验证依据，即该帐号只能操作它自己的店铺
			request.getSession().setAttribute("shopList", se.getShopList());
			modelMap.put("user", user);
			modelMap.put("success", true);
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
		}
		return modelMap;
	}
	
	
	@RequestMapping(value = "/getshopbyid", method = RequestMethod.GET)
	@ResponseBody
	private Map<String,Object> getShopById(HttpServletRequest request){
		Map<String,Object>modelMap=new HashMap<String,Object>();//定义返回值变量
		Long shopId=HttpServletRequestUtil.getLong(request, "shopId");
		
		if(shopId>-1){
			try{
				Shop shop=shopService.getByShopId(shopId);
				List<Area>areaList=areaService.getAreaList();//huo获取区域列表
				modelMap.put("shop", shop);
				modelMap.put("areaList", areaList);
				modelMap.put("success", true);
			}catch(Exception e){
				modelMap.put("success", false);
				modelMap.put("errMsg", e.toString());
			}
			
		}else{//如果＜-1则是失败
			modelMap.put("success", false);
			modelMap.put("errMsg", "empty shopId");
		}
		return modelMap;
	}
	
	
	@RequestMapping(value = "/getshopinitinfo", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getShopInitInfo() {
		Map<String, Object> modelMap = new HashMap<String, Object>();//d定义一个modelmap对象，用一个shopcategorylis来接受相关信息
		List<ShopCategory> shopCategoryList = new ArrayList<ShopCategory>();
		List<Area> areaList = new ArrayList<Area>();//用arealist接受区域相关信息
		try {
			shopCategoryList = shopCategoryService.getShopCategoryList(new ShopCategory());
			areaList = areaService.getAreaList();
			modelMap.put("shopCategoryList", shopCategoryList);
			modelMap.put("areaList", areaList);
			modelMap.put("success", true);
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
		}
		return modelMap;
	}

	@RequestMapping(value = "/registershop", method = RequestMethod.POST)
	@ResponseBody // zi自动转换成json对象
	private Map<String, Object> registershop(HttpServletRequest request) {
		
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if (!CodeUtil.checkVerifyCode(request)) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "输入了错误的验证码");
			return modelMap;//判断是否验证码输入正确
		}
		// 1jie接收并转换相应的参数,包括店铺信息以及图片信息
		String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
		ObjectMapper mapper = new ObjectMapper();
		Shop shop = null;// dingyi定义一个实体类去接受
		try {
			shop = mapper.readValue(shopStr, Shop.class);
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
			return modelMap;
		}
		CommonsMultipartFile shopImg = null;
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (commonsMultipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
			shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "上传图片不能为空");
			return modelMap;
		}
		// 2注册店铺
		if (shop != null && shopImg != null) {
			//PersonInfo owner = new PersonInfo();
			PersonInfo owner =(PersonInfo)request.getSession().getAttribute("user");//husession获取当前用户信息
			
			shop.setOwner(owner);
//			File shopImgFile=new File(PathUtil.getImgBasePath()+ImageUtil.getRandomFileName());
//			try{
//				shopImgFile.createNewFile();
//			}catch(IOException e){
//				modelMap.put("success", false);
//				modelMap.put("errMsg", e.getMessage());
//				return modelMap;
//			}
//			try {
//				inputStreamToFile(shopImg.getInputStream(),shopImgFile);
//			} catch (IOException e) {
//				modelMap.put("success", false);
//				modelMap.put("errMsg", e.getMessage());
//				return modelMap;
//			}
			ShopExecution se;
			try {
				ImageHolder imageHolder=new ImageHolder(shopImg.getOriginalFilename(),shopImg.getInputStream());
				se = shopService.addShop(shop, imageHolder);
				if(se.getState()==ShopStateEnum.CHECK.getState()){
					modelMap.put("success", true);
					//yid一旦店铺创建成功就保存到session中
					//从session中取出用户可以操作的店铺列表
					@SuppressWarnings("unchecked")
					List<Shop>shopList=(List<Shop>)request.getSession().getAttribute("shopList");
					if(shopList==null||shopList.size()==0){
						shopList=new ArrayList<Shop>();//rg如果没有创建过，就创建一个新的shoplist
						}
						shopList.add(se.getShop());
						request.getSession().setAttribute("shopList", shopList);//cun存回session中
					
					
				}else{
					modelMap.put("false", false);
					modelMap.put("errMsg", se.getStateInfo());//getStateInfo返回状态注释，为什么会出错
				}
			} catch (ShopOperationException e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
			} catch (IOException e) {
				modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
			}//huo获取原本的文件名字
			
			return modelMap;
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "请输入店铺信息");
			return modelMap;
		}
		// 3返回结果

	}
	@RequestMapping(value = "/modifyshop", method = RequestMethod.POST)
	@ResponseBody // zi自动转换成json对象
	private Map<String, Object> modifyshop(HttpServletRequest request) {
		
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if (!CodeUtil.checkVerifyCode(request)) {
			modelMap.put("success", false);
			modelMap.put("errMsg", "输入了错误的验证码");
			return modelMap;//判断是否验证码输入正确
		}
		// 1jie接收并转换相应的参数,包括店铺信息以及图片信息
		String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
		ObjectMapper mapper = new ObjectMapper();
		Shop shop = null;// dingyi定义一个实体类去接受
		try {
			shop = mapper.readValue(shopStr, Shop.class);
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
			return modelMap;
		}
		CommonsMultipartFile shopImg = null;
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (commonsMultipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
			shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
		} 
		// 2xiug修改店铺信息
		if (shop != null &&shop.getShopId()!=null ) {	
			ShopExecution se;
			try {
				if(shopImg==null){//fei非空判断，为空就传null
					se=shopService.modifyShop(shop, null);
				}else{
					ImageHolder imageHolder=new ImageHolder(shopImg.getOriginalFilename(),shopImg.getInputStream());
				se = shopService.modifyShop(shop, imageHolder);
				
				}
				if(se.getState()==ShopStateEnum.SUCCESS.getState()){
					modelMap.put("success", true);
				}else{
					modelMap.put("false", false);
					modelMap.put("errMsg", se.getStateInfo());//getStateInfo返回状态注释，为什么会出错
				}
			} catch (ShopOperationException e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
			} catch (IOException e) {
				modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
			}//huo获取原本的文件名字
			
			return modelMap;
		} else {
			modelMap.put("success", false);
			modelMap.put("errMsg", "请输入店铺信息");
			return modelMap;
		}
		// 3返回结果
	}
//	private static void inputStreamToFile(InputStream ins, File file) {
//		FileOutputStream os = null;
//		try {
//			os = new FileOutputStream(file);
//			int bytesRead = 0;
//			byte[] buffer = new byte[1024];
//			while ((bytesRead = ins.read(buffer)) != -1) {
//				os.write(buffer, 0, bytesRead);
//
//			}
//
//		} catch (Exception e) {
//			throw new RuntimeException("调用inputStreamToFile产生异常" + e.getMessage());
//		} finally {
//			try {
//				if (os != null) {
//					os.close();
//				}
//				if (ins != null) {
//					ins.close();
//				}
//			} catch (IOException e) {
//				throw new RuntimeException("inputStreamToFile关闭io产生异常" + e.getMessage());
//
//			}
//		}
//
//	}
}
